﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Koonsoft.CustomerService.Entity;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace Koonsoft.CustomerService.DAL
{
    public class IssueAccessoriesDAL
    {
        private Database database = DatabaseFactory.CreateDatabase("CustomerService");
        public bool Create(IssueAccessorie acc, out string msg)
        {
            msg = "";

            const string sql = @"insert into [IssueAccessories]([IssueID],[Accessory],[AccessoryName])
                                    values(@IssueID,@Accessory,@AccessoryName)";

            try
            {
                using (var cmd = database.GetSqlStringCommand(sql))
                {
                    database.AddInParameter(cmd, "@IssueID", DbType.Guid , acc.IssueId);
                    database.AddInParameter(cmd, "@Accessory", DbType.String, acc.Accessory);
                    database.AddInParameter(cmd, "@AccessoryName", DbType.String, acc.AccessoryName);
                    return database.ExecuteNonQuery(cmd) > 0;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message + ";" + ex.StackTrace;
            }
            return false;
        }

        public List<IssueAccessorie> GetIssueAccessorie(Guid guid, out string msg)
        {
            msg = "";
            string sql = @"select * from  [IssueAccessories] where [IssueID] =@IssueID";

            List<IssueAccessorie> issueAccessories = new List<IssueAccessorie>();
            try
            {
                using (var cmd = database.GetSqlStringCommand(sql))
                {
                    database.AddInParameter(cmd, "@IssueID", DbType.Guid, guid);

                    DataTable dt = database.ExecuteDataSet(cmd).Tables[0];

                    foreach (DataRow dr in dt.Rows)
                    {
                        IssueAccessorie Acc = new IssueAccessorie();
                        Acc.IssueId = guid;
                        Acc.Accessory = dr["Accessory"].ToString();
                        Acc.AccessoryName = dr["AccessoryName"].ToString();
                        issueAccessories.Add(Acc);
                    }

                    return issueAccessories;
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message + ";" + ex.StackTrace;
            }
            return new List<IssueAccessorie>();
        }
    }
}
